import { useIndicatorsByPoint } from './MixinIndicatorsByPoint'

import {
  queryDataSourceConfigsByPointId,
  saveOrUpdateDataSourceConfig,
} from '@/api/modules/dataSourceConfiguration'

import type { Nullable } from '@/types'
import type { StatisticalIndicator } from '@/types/modules/statistical-indicator'

export interface DataSourceConfig {
  id: number
  /** 参数Key */
  parameterKey: string
  /** 参数Value */
  parameterValue: string
  /** 指标名称编码 */
  indicatorNumber: Nullable<string>
  /** 指标名称 */
  indicatorName: Nullable<string>
  /** 测点编码 */
  measuringPointNumber: Nullable<string>
  /** 指标单位 */
  unit: Nullable<string>
  /** 用能单元ID */
  energyUnitId: number
  /** 存储周期 */
  storageMode: StatisticalIndicator['storageMode']
}

export type IndicatorWithDisabled =
  Pick<StatisticalIndicator, 'indicatorName' | 'indicatorNumber' | 'indicatorCode' | 'storageMode'>
  & { disabled: boolean }
  & { unit: string }

export function useDataSourceConfigs() {
  const [lists, setLists] = useState<Partial<DataSourceConfig>[]>([])
  const {
    lists: indicators,
    getIndicatorsByPointId,
  } = useIndicatorsByPoint()
  const [saving, setSaving] = useState(false)
  const [loading, setLoading] = useState(false)
  // const [indicatorLists, setIndicatorLists] = useState<IndicatorWithDisabled[]>([])

  const indicatorLists = computed<IndicatorWithDisabled[]>(() => {
    const numbers = unref(lists).map(v => v.indicatorNumber!)
    const result: IndicatorWithDisabled[] = unref(indicators).map(v => ({
      indicatorName: v.indicatorName!,
      indicatorNumber: v.indicatorNumber!,
      indicatorCode: v.indicatorCode!,
      unit: v.unitName!,
      storageMode: v.storageMode!,
      disabled: numbers.includes(v.indicatorNumber!),
    }))
    return result
  })

  function getStorageMode(indicatorNumber: string) {
    const t = unref(indicatorLists).find(i => i.indicatorNumber === indicatorNumber)
    return t?.storageMode
  }

  async function getConfigsByPointId(pointId: number) {
    setLoading(true)
    try {
      const res = await queryDataSourceConfigsByPointId(pointId);
      (res.data || []).forEach((item: any) => {
        item.energyUnitId = pointId
        item.storageMode = getStorageMode(item.indicatorNumber)
      })
      setLists(res.data || [])
    }
    catch (e) {
      console.warn(e)
    }
    finally {
      setLoading(false)
    }
  }

  async function save() {
    const params = unref(lists)
    // console.log(params)
    setSaving(true)
    try {
      await saveOrUpdateDataSourceConfig(params)
      ElMessage.success('保存成功')
    }
    catch (e) {
      console.warn(e)
    }
    finally {
      setSaving(false)
    }
  }

  return {
    lists,
    setLists,
    /** 根据用能单元ID查询数据源配置列表数据 */
    getConfigsByPointId,
    indicatorLists,

    /** 根据用能单元ID查询对应的指标列表数据 */
    getIndicatorsByPointId,
    saving,
    setSaving,
    save,
    loading,
  }
}
